<template>
  <a-modal switchFullscreen :maskClosable="false" :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading"  @cancel="handleCancel" cancelText="关闭">
    <a-steps :current="currentStep">
      <a-step title="资源定义" />
      <a-step title="数据选择" />
      <a-step title="字段映射" />
      <a-step title="同步规则" />
    </a-steps>
    <div style="width: 100%;height: 20px;" />
    <FileDataForm ref="fileDataForm" v-show="currentStep == 0"  />
    <CsvDataForm ref="csvDataForm" v-show="currentStep == 1 && (fileType == 'csv')"  />
    <ExcelDataForm ref="excelDataForm" v-show="currentStep == 1 && (fileType == 'excel')"  />
    <TxtDataForm ref="txtDataForm" v-show="currentStep == 1 && (fileType == 'txt')" />

    <FileDataTableAddForm ref="fileDataTableAddForm" v-show="currentStep == 2 && createTable == 1" />
    <FileDataTableEditForm ref="fileDataTableEditForm" v-show="currentStep == 2 && createTable == 0" />
    <FileDataImportMode ref="fileDataImportMode" v-show="currentStep == 3" />

    <template slot="footer">
      <a-button v-if="currentStep > 0" @click="stepsPrev">上一步</a-button>
      <a-button v-if="currentStep === 0 || currentStep === 1 || currentStep === 2" @click="nextPrev">下一步</a-button>
      <a-button type="primary" @click="handleImportData" :loading="submitLoading" v-if="currentStep == 3">开始导入</a-button>
    </template>
  </a-modal>
</template>

<script>
import { randomUUID, simpleDebounce } from '@/utils/util.js'
import { setDataSource, getMasterTableInitialData, getTreeNeedFields } from '../util/TableUtils'
import FileDataForm from './FileDataForm'
import CsvDataForm from './CsvDataForm'
import ExcelDataForm from './ExcelDataForm'
import TxtDataForm from './TxtDataForm'

import FileDataTableAddForm from './FileDataTableAddForm'
import FileDataTableEditForm from './FileDataTableEditForm'
import FileDataImportMode from './FileDataImportMode'
import { getAction, postAction } from '@/api/manage'
export default {
  name: 'SysDataSourceModal',
  components: {
    FileDataForm,
    CsvDataForm,
    ExcelDataForm,
    FileDataTableAddForm,
    FileDataTableEditForm,
    FileDataImportMode,
    TxtDataForm
  },
  data() {
    return {
      importParam: {},
      analysisJson: {},
      createTable: null,
      baseForm: {},
      filePrefix: '/data/situation/static/upload/',
      fileType: '',
      currentStep: 0,
      title: '操作',
      visible: false,
      model: {},
      confirmLoading: false,
      submitLoading: false
    }
  },
  created() {
  },
  methods: {
    stepsPrev() {
      this.currentStep--
    },
    nextPrev() {
      if (this.currentStep == 0) {
        this.handleFile()
      } else if (this.currentStep == 1) {
        if (this.fileType == 'csv') {
          this.handleCsv()
        } else if (this.fileType == 'excel') {
          this.handleExcel()
        } else if (this.fileType == 'txt') {
          this.handleTxt()
        }
      } else if (this.currentStep == 2) {
        this.handleAddData()
      }
    },
    handleFile() {
      this.$refs.fileDataForm.form.validateFields((err, values) => {
        if (!err) {
          if ((!this.$refs.fileDataForm.fileList || this.$refs.fileDataForm.fileList.length == 0)) {
            this.$message.warning('上传文件不能为空')
            return
          }
          var fileTemp = this.$refs.fileDataForm.fileList.split('.')
          this.fileType = fileTemp[fileTemp.length - 1].toLowerCase()
          if (this.fileType == 'xls' || this.fileType == 'xlsx') {
            this.fileType = 'excel'
          }
          this.baseForm = {
            fileName: values.fileName,
            fileType: this.fileType,
            filePath: this.$refs.fileDataForm.fileList
          }
          // 判断是不是excell
          if (this.fileType == 'excel') {
            // 获取sheet页
            getAction('/dataSource/scDataFile/getExcelSheet', { 'filePath': this.$refs.fileDataForm.fileList }).then(res => {
              if (res.success) {
                var sheets = []
                for (var i in res.result) {
                  sheets.push({
                    value: res.result[i],
                    name: i
                  })
                }
                this.$refs.excelDataForm.setSheets(sheets)
                this.currentStep++
              }
            })
          } else {
            if (this.fileType == 'csv') {
              this.$refs.csvDataForm.form.setFieldsValue({ 'lineSep': 'CRLF' })
            } else {
              this.$refs.txtDataForm.form.setFieldsValue({ 'lineSep': 'CRLF' })
            }
            this.currentStep++
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 处理新增表
    handleAddData() {
      var formTemp = 'fileDataTableAddForm'
      if (this.createTable != 1) {
        formTemp = 'fileDataTableEditForm'
      }
      this.$refs[formTemp].form.validateFields((err, values) => {
        console.log(err)
        console.log(values)
        if (!err) {
          var fileDataTable = this.$refs[formTemp].getTableData()
          if (fileDataTable.error == 0) {
            var tableMapping = []
            fileDataTable.values.forEach((item, index) => {
              if (index > 0) {
                tableMapping.push({
                  'fieldName': item.columnName,
                  'columnIndex': item.fieldIndex,
                  'columnName': item.fieldName
                })
              }
              item.sort = index + 1
            })
            var params = this.baseForm
            params.tableId = values.tableId
            // situation data
            this.analysisJson.dataSource = 'situation_data'
            this.analysisJson.tableMapping = tableMapping

            this.analysisJson.createTable = this.createTable

            if (this.createTable != 1) {
              this.analysisJson.tableId = values.tableId
              this.analysisJson.tableName = this.$refs[formTemp].tableName
              params.scSituationTable = {
                tableName: this.$refs[formTemp].tableName,
                dataSource: 'situation_data',
                columns: fileDataTable.values,
                status: 1,
                tableType: 3,
                tableId: values.tableId,
                id: values.tableId
              }
            } else {
              this.analysisJson.tableName = values.tableName
              params.scSituationTable = {
                tableName: values.tableName,
                dataSource: 'situation_data',
                columns: fileDataTable.values,
                status: 1,
                tableType: 3
              }
            }

            params.analysisJsonString = JSON.stringify(this.analysisJson)
            this.importParam = params

            this.currentStep++
          } else {
            this.confirmLoading = false
            return
          }
        }
      })
    },
    handleImportData() {
      this.submitLoading = true
      this.importParam.importType = this.$refs.fileDataImportMode.importType
      postAction('/dataSource/scDataFile/importFileData', this.importParam).then(res => {
        console.log(res)
        if (res.success) {
          this.close()
        }
        this.submitLoading = false
      })
    },
    handleExcel() {
      this.$refs.excelDataForm.form.validateFields((err, values) => {
        if (!err) {
          // /dataSource/scDataFile/fileParse
          var params = this.baseForm
          this.analysisJson = values
          params.fileType = 'excel'
          this.createTable = values.createTable
          params.analysisJsonString = JSON.stringify(this.analysisJson)
          postAction('/dataSource/scDataFile/fileParse', params).then(res => {
            if (res.success) {
              this.initTable(res.result)
            }
          })
        }
      })
    },
    // 处理txt文件表头
    handleTxt() {
      this.$refs.txtDataForm.form.validateFields((err, values) => {
        if (!err) {
          // /dataSource/scDataFile/fileParse
          console.log('values-----------------------------------', values)
          var params = this.baseForm
          this.analysisJson = values
          this.createTable = values.createTable
          this.analysisJson.columnSepType = 'sep'
          params.analysisJsonString = JSON.stringify(this.analysisJson)
          postAction('/dataSource/scDataFile/fileParse', params).then(res => {
            if (res.success) {
              this.initTable(res.result)
            }
          })
        }
      })
    },
    // 处理csv文件表头
    handleCsv() {
      this.$refs.csvDataForm.form.validateFields((err, values) => {
        if (!err) {
          // /dataSource/scDataFile/fileParse
          console.log('values-----------------------------------', values)
          var params = this.baseForm
          this.analysisJson = values
          this.createTable = values.createTable
          this.analysisJson.columnSepType = 'sep'
          params.analysisJsonString = JSON.stringify(this.analysisJson)
          postAction('/dataSource/scDataFile/fileParse', params).then(res => {
            if (res.success) {
              this.initTable(res.result)
            }
          })
        }
      })
    },
    initTable(values) {
      var tableData = this.initId()
      if (this.fileType == 'excel') {
        for (var i in values) {
          tableData.push({
            fieldIndex: values[i],
            fieldName: i
          })
        }
      } else {
        for (var i1 in values) {
          tableData.push({
            fieldIndex: i1,
            fieldName: values[i1]
          })
        }
      }

      this.$refs.fileDataTableAddForm.fileName = this.baseForm.fileName
      this.$refs.fileDataTableEditForm.fileName = this.baseForm.fileName
      if (this.createTable == 1) {
        this.$refs.fileDataTableAddForm.initValues(tableData)
      } else {
        this.$refs.fileDataTableEditForm.initValues(tableData)
      }

      this.currentStep++
    },
    initId() {
      const tempIds = []
      const datas = getMasterTableInitialData()
      datas.forEach(data => {
        data.id = randomUUID()
        tempIds.push(data.id)
      })
      this.fieldTempIds = tempIds
      return [{
        id: datas[0].id,
        columnName: datas[0].dbFieldName,
        columnComment: datas[0].dbFieldTxt,
        columnLength: datas[0].dbLength,
        scale: datas[0].dbPointLength,
        defaultValue: datas[0].dbDefaultVal,
        columnType: datas[0].dbType,
        isPk: datas[0].dbIsKey,
        isNullable: datas[0].dbIsNull,
        sort: 0
      }]
    },
    add() {
      this.visible = true
      this.currentStep = 0
    },
    close() {
      this.$emit('ok')
      this.visible = false
      this.$refs.fileDataForm.fileList = []
      this.$refs.fileDataForm.form.resetFields()
      this.$refs.csvDataForm.form.resetFields()
      this.$refs.excelDataForm.form.resetFields()
      this.$refs.fileDataTableAddForm.form.resetFields()
      this.$refs.fileDataTableEditForm.form.resetFields()
      this.$refs.fileDataImportMode.form.resetFields()
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style lang="less" scoped>
.atn-testbtn {
    color: #2F77F2 !important;
    background: #FFFFFF !important;
    box-shadow: 0px 1px 3px 0px rgba(4, 0, 0, 0.08) !important;
    border: 1px solid #2F77F2 !important;
    border-radius: 2px !important;
    padding: 0 10px !important;
    height: 34px !important;
    margin: 0 8px 8px 0;
}
</style>
